<?php

namespace Home\Model;

class PlayerModel extends CommonModel {

    public function findPlayer($userid){
        $flt = array(
            'user_id' => $userid,
        );
        $rs = $this->where($flt)->find();
        if (!empty($rs)) {
            $position = $this->decodePosition($rs);
            $rs['position_y'] = $position[0];
            $rs['position_x'] = $position[1];
        }
        return $rs;
    }

    public function findPlayers($playerIds){
        $ids = array();
        foreach ($playerIds as $k => $v) {
            $ids[] = $v['player_id'];
        }
        $flt = array(
            'player_id' => array('in', $ids),
        );
        $rs = $this->where($flt)->select();
        return $rs;
    }

    public function savePlayer(){
        if (empty($_POST['player_id'])) {
            // insert
            $this->_auto = array(
                array('position','encodePosition',1,'callback'),
                array('create_time','time',1,'function'),
                array('update_time','time',3,'function'),
            );
        } else {
            // update
            $this->_auto = array(
                array('position','encodePosition',1,'callback'),
                array('update_time','time',3,'function'),
            );
        }

        $dt = $this->create();
        if (empty($_POST['player_id'])) {
            $rs = $this->add($dt);
        } else {
            $rs = $this->save($dt);
        }

        $ret = array();
        if ($rs) {
            $ret['status'] = true;
            $ret['msg'] = '操作成功！';
        } else {
            $ret['status'] = false;
            $ret['msg'] = $this->getError();
        }
        return $ret;
    }

    public function encodePosition(){
        return $_POST['position_y'] . '-' . $_POST['position_x'];
    }

    public function decodePosition($rs){
        $dt = explode('-', $rs['position']);
        return $dt;
    }
}
